package ws

import (
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/tools"
	"github.com/gorilla/websocket"
	"time"
)

func CreateRdsKeyGroupSessions(group string) string {
	return fmt.Sprintf("GroupSessions:%s", group)
}

// CreateGroup 创建一个组，并把当前用户加入进去，暂时不可以无用户创建组
func CreateGroup(group string, session string) string {
	if group == "" {
		group = tools.CreateRandString(7)
	}
	k := CreateRdsKeyGroupSessions(group)
	//将SessionId GroupSessions::__GROUP_KEY__ Set中
	cmd := ez.GetRedis().SAdd(k, session)
	if cmd.Err() != nil {
		ez.Debug(cmd.Err())
	}
	ez.GetRedis().Expire(k, time.Hour*12)
	return group
}

// JoinGroup 将SessionId 添加到 GroupSessions::__GROUP_KEY__ Set中
func JoinGroup(group string, session string) error {
	k := CreateRdsKeyGroupSessions(group)
	cmd := ez.GetRedis().SAdd(k, session)
	if cmd.Err() != nil {
		ez.Debug(cmd.Err())
	}
	ez.GetRedis().Expire(k, time.Hour*12)
	return cmd.Err()
}

// LeaveGroup 把SessionId 从 GroupSessions::__GROUP_KEY__ Set中移除
func LeaveGroup(group string, session string) error {
	k := CreateRdsKeyGroupSessions(group)
	//将SessionId GroupSessions::__GROUP_KEY__ Set中
	cmd := ez.GetRedis().SRem(k, session)
	if cmd.Err() != nil {
		ez.Debug(cmd.Err())
	}
	ez.GetRedis().Expire(k, time.Hour*12)
	return cmd.Err()
}

func (hub *Hub) GetGroupSessions(group string) []string {
	cmd := ez.GetRedis().SMembers(CreateRdsKeyGroupSessions(group))
	if cmd.Err() != nil {
		ez.Debug(cmd.Err())
		return nil
	}
	wanted := make([]string, 0)
	e := cmd.ScanSlice(&wanted)
	if e != nil {
		ez.Debug(e)
		return nil
	}
	return wanted
}

func PushToGroup(group string, data []byte) {
	sessionIds := ezhub.GetGroupSessions(group)
	for _, sessionId := range sessionIds {
		session := ezhub.GetSession(sessionId)
		if session != nil {
			err := session.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				//断开的session 从全局中删除
				ezhub.RemoveSession(session)
			}
		} else {
			//无效的sessionId需要从用户列表中清除
			LeaveGroup(group, sessionId)
		}
	}
}

func PushToAll(data []byte) {
	count := 0
	for _, session := range ezhub.Sessions {
		if session != nil {
			err := session.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				//断开的session 从全局中删除
				ezhub.RemoveSession(session)
			} else {
				count++
			}
		}
		if count > ezhub.MaxBroadCastCount {
			count = 0
			time.Sleep(time.Millisecond * time.Duration(ezhub.MaxBroadCastSleep))
		}
	}
}
